/*
 * @lc app=leetcode.cn id=508 lang=typescript
 *
 * [508] 出现次数最多的子树元素和
 */

// @lc code=start
/**
 * Definition for a binary tree node.
 * class TreeNode {
 *     val: number
 *     left: TreeNode | null
 *     right: TreeNode | null
 *     constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) {
 *         this.val = (val===undefined ? 0 : val)
 *         this.left = (left===undefined ? null : left)
 *         this.right = (right===undefined ? null : right)
 *     }
 * }
 */

function findFrequentTreeSum(root: TreeNode | null): number[] {
  const cnt = new Map<number, number>();
  let maxCnt = 0;
  const dfs = (root: TreeNode | null): number => {
    if (root === null) return 0;
    const left = dfs(root.left);
    const right = dfs(root.right);
    const sum = root.val + left + right;
    cnt.set(sum, (cnt.get(sum) || 0) + 1);
    maxCnt = Math.max(maxCnt, cnt.get(sum) || 0);
    return sum;
  };
  dfs(root);
  const ans: number[] = [];
  for (const [k, v] of cnt) {
    if (v === maxCnt) ans.push(k);
  }
  return ans;
}
// @lc code=end
